<?php

/**
 * ECSHOP 支持淘宝接口函数库
 * ============================================================================
 * 版权所有 2005-2010 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liuhui $
 * $Id: lib_payment.php 17063 2010-03-25 06:35:46Z liuhui $
 */

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

/* 语言项 */

//订单部分
$_LANG['WAIT_BUYER_PAY'] = '等待买家付款';
$_LANG['WAIT_SELLER_SEND_GOODS'] = '等待卖家发货,即:买家已付款';
$_LANG['WAIT_BUYER_CONFIRM_GOODS'] = '等待买家确认收货';
$_LANG['TRADE_BUYER_SIGNED'] = '买家已签收';
$_LANG['TRADE_FINISHED'] = '交易成功';
$_LANG['taobao'] = '淘宝网站交易';
$_LANG['taobao_import'] = '导入淘宝订单';
$_LANG['taobao_rate'] = '评价情况';
$_LANG['buyer_rate_t'] = '买家已评';
$_LANG['buyer_rate_f'] = '买家未评';
$_LANG['seller_rate_t'] = '卖家已评';
$_LANG['seller_rate_f'] = '评价';
$_LANG['login_taobao'] = '点击此处进行淘宝登陆';
$_LANG['config_taobao'] = '请在商店设置中，开启淘宝同步管理选项！';
$_LANG['taobao_rate'] = '评价结果';
$_LANG['rate_good'] = '好评';
$_LANG['rate_neutral'] = '中评';
$_LANG['rate_bad'] = '差评';


//商品部分
$_LANG['tb_retry'] = '您的淘宝商品上传未成功，您可以修改参数后重试。参考信息为：';
$_LANG['tb_choose_prop'] = '请选择属性';
$_LANG['tb_sale_props'] = '商品销售属性';
$_LANG['tb_sale_price'] = '销售价';
$_LANG['tb_shipping_model_notice'] = '您还没有创建模板，请选择其他方式';
$_LANG['tb_choose_model'] = '请选择模板';
$_LANG['tb_choose_cat'] = '请选择类目';
$_LANG['tb_year'] = '年';
$_LANG['tb_month'] = '月';
$_LANG['tb_day'] = '日';
$_LANG['tb_cat_explain_1'] = '当前类目为';
$_LANG['tb_cat_explain_2'] = ',点击重新选择类目';
$_LANG['tb_get_cat'] = '点击获取类目';
$_LANG['tb_cats'] = '宝贝类目';
$_LANG['tb_have'] = '有';
$_LANG['tb_havenot'] = '无';
$_LANG['tb_recommend'] = '橱窗推荐';
$_LANG['tb_auto_retry'] = '自动重发';
$_LANG['tb_warranty'] = '保修';
$_LANG['tb_invoice'] = '发票';
$_LANG['tb_storage'] = '放入仓库';
$_LANG['tb_minute'] = '分';
$_LANG['tb_hour'] = '时';
$_LANG['tb_set'] = '设定';
$_LANG['tb_now'] = '立刻';
$_LANG['tb_die_day'] = '有效期';
$_LANG['tb_have_member_discount'] = '参与会员打折';
$_LANG['tb_no_member_discount'] = '不参与会员打折';
$_LANG['tb_discount'] = '会员打折';
$_LANG['tb_yuan'] = '元';
$_LANG['tb_shipping_express'] = '快递';
$_LANG['tb_shipping_normal'] = '平邮';
$_LANG['tb_use_shipping_model'] = '使用运费模板';
$_LANG['tb_buyer_shipping'] = '买家承担运费';
$_LANG['tb_seller_shipping'] = '卖家承担运费';
$_LANG['tb_shipping_fee'] = '运费';
$_LANG['tb_desc'] = '宝贝描述';
$_LANG['tb_city'] = '城市';
$_LANG['tb_stay'] = '所在地';
$_LANG['tb_piece'] = '件';
$_LANG['tb_goods_num'] = '宝贝数量';
$_LANG['tb_seller_code'] = '商家编码';
$_LANG['tb_fixed_price'] = '一口价';
$_LANG['tb_goods_title'] = '宝贝标题';
$_LANG['tb_old_goods'] = '个人闲置';
$_LANG['tb_second_hand'] = '二手';
$_LANG['tb_new_goods'] = '全新';
$_LANG['tb_goods_types'] = '宝贝类型';
$_LANG['tb_goods_infos'] = '商品基本信息';
$_LANG['tb_put_goods_to_tb'] = '同步发布商品到淘宝';
$_LANG['tb_put_to_tb'] = '发布到淘宝';
$_LANG['login_taobao'] = '点击此处进行淘宝登陆';
$_LANG['day'] = '天';
$_LANG['tb_start_date'] = '开始时间';
$_LANG['tb_auction_point'] = '返点比例';

$smarty->assign('lang', $_LANG);

/* 初始化公用参数和载入相应文件 */
function taobao_init()
{
    global $taobao, $tb_session;

    include_once(ROOT_PATH . 'includes/modules/taobao/includes/cls_taobao.php');

    $taobao = new taobao($GLOBALS['_CFG']['certificate_id']);

    $sql = "SELECT session FROM " . $GLOBALS['ecs']->table('taobao') . " order by id desc";
    $tb_session = $GLOBALS['db']->getOne($sql);
}


/* 向前台传递商品的淘宝相关数据 */
function show_taobao()
{
    global $smarty;

    if (!empty($GLOBALS['goods']['tb_iid']))
    {
        $smarty->assign('tb_iid', $GLOBALS['goods']['tb_iid']);

        $tb_data = unserialize($GLOBALS['goods']['tb_data']);

        $smarty->assign('tb_data', $tb_data);

        $tb_cat_data = explode('|', $tb_data['tb_cid']);
        $smarty->assign('tb_cat_id', substr($tb_cat_data[0], 2));
        $smarty->assign('tb_cat_name', $tb_cat_data[1]);
    }

    $smarty->assign('tb_use', $GLOBALS['_CFG']['taobao_syn']);

}


/* 处理提交的商品淘宝内容 */
function deal_taobao()
{
    global $_POST, $tb_session, $taobao, $db, $tb_result, $tb_wrong, $original_img, $tb_original_img, $ecs, $goods_id;

    if (!empty($_POST['puttotb']))
    {
        $tb_goods_from = empty($_POST['tb_goods_from']) ? '' : intval($_POST['tb_goods_from']);
        $tb_goods_name = empty($_POST['tb_goods_name']) ? '' : trim($_POST['tb_goods_name']);
        $tb_goods_price = empty($_POST['tb_goods_price']) ? '' : floatval($_POST['tb_goods_price']);
        $tb_auction_point = empty($_POST['tb_auction_point']) ? '' : intval($_POST['tb_auction_point']);
        $tb_seller_code = empty($_POST['tb_seller_code']) ? '' : trim($_POST['tb_seller_code']);
        $tb_goods_mount = empty($_POST['tb_goods_mount']) ? '' : intval($_POST['tb_goods_mount']);
        $tb_goods_province = empty($_POST['tb_goods_province']) ? '' : trim($_POST['tb_goods_province']);
        $tb_goods_city = empty($_POST['tb_goods_city']) ? '' : trim($_POST['tb_goods_city']);
        $tb_desc = empty($_POST['tb_desc']) ? '' : trim($_POST['tb_desc']);
        $tb_pay_shipping = empty($_POST['tb_pay_shipping']) ? '' : intval($_POST['tb_pay_shipping']);
        $tb_shipping_model = empty($_POST['tb_shipping_model']) ? '' : trim($_POST['tb_shipping_model']);
        $tb_shipping_normal = empty($_POST['tb_shipping_normal']) ? '' : floatval($_POST['tb_shipping_normal']);
        $tb_shipping_express = empty($_POST['tb_shipping_express']) ? '' : floatval($_POST['tb_shipping_express']);
        $tb_shipping_ems = empty($_POST['tb_shipping_ems']) ? '' : floatval($_POST['tb_shipping_ems']);
        $tb_has_discount = empty($_POST['tb_has_discount']) ? '' : intval($_POST['tb_has_discount']);
        $tb_valid_thru = empty($_POST['tb_valid_thru']) ? '' : intval($_POST['tb_valid_thru']);
        $_now = empty($_POST['_now']) ? '' : intval($_POST['_now']);
        $_date = empty($_POST['_date']) ? '' : trim($_POST['_date']);
        $_hour = empty($_POST['_hour']) ? '' : trim($_POST['_hour']);
        $_minute = empty($_POST['_minute']) ? '' : trim($_POST['_minute']);
        $tb_has_invoice = empty($_POST['tb_has_invoice']) ? '' : intval($_POST['tb_has_invoice']);
        $tb_has_warranty = empty($_POST['tb_has_warranty']) ? '' : intval($_POST['tb_has_warranty']);
        $tb_auto_repost = empty($_POST['tb_auto_repost']) ? '' : intval($_POST['tb_auto_repost']);
        $tb_has_showcase = empty($_POST['tb_has_showcase']) ? '' : intval($_POST['tb_has_showcase']);
        $tb_cid = empty($_POST['tb_cid']) ? '' : $_POST['tb_cid'];


        $session = $tb_session;
        $params = array();

        $params['num'] = $tb_goods_mount;
        $params['price'] = $tb_goods_price;
        $params['auction_point'] = $tb_auction_point;
        $params['type'] = 'fixed';
        $params['stuff_status'] = $tb_goods_from == 3 ? 'unused' : ($tb_goods_from == 2 ? 'second' : 'new');
        $params['title'] = $tb_goods_name;
        $params['desc'] = $tb_desc;
        $params['location.state'] = $tb_goods_province;
        $params['location.city'] = $tb_goods_city;


        if (!empty($tb_cid))
        {
            foreach ($tb_cid as $key => $val)
            {
                if (!empty($val) && empty($val[0]))
                {
                    $params['cid'] = substr($val, 2, (strpos($val, '|')-2));
                    $org_cat_data = $val;
                    break;
                }
            }
        }

        if ($tb_pay_shipping == 1)
        {
            if (empty($tb_shipping_model))
            {
                $params['post_fee'] = empty($tb_shipping_normal) ? '0.00' : number_format($tb_shipping_normal, 2);
                $params['express_fee'] = empty($tb_shipping_express) ? '0.00' : number_format($tb_shipping_express, 2);
                $params['ems_fee'] = empty($tb_shipping_ems) ? '0.00' : number_format($tb_shipping_ems, 2);
            }
            else
            {
                $params['postage_id'] = $tb_shipping_model;
            }
            $params['freight_payer'] = 'buyer';
        }
        else
        {
            $params['freight_payer'] = 'seller';
        }

        if ($_now == 2)
        {
            $params['approve_status'] = 'instock';
        }
        elseif ($_now == 1)
        {
            $tb_time_temp = explode('-', $_date);
            $tb_time_temp[1] = empty($tb_time_temp[1][1]) ? '0' . $tb_time_temp[1][0] : $tb_time_temp[1];
            $tb_time_temp[2] = empty($tb_time_temp[2][1]) ? '0' . $tb_time_temp[2][0] : $tb_time_temp[2];
            $_date = implode('-', $tb_time_temp);
            $_hour = empty($_hour[1]) ? '0' . $_hour[0] : $_hour;
            $_minute = empty($_minute[1]) ? '0' . $_minute[0] : $_minute;
            $params['list_time'] = "{$_date} {$_hour}:{$_minute}:00";
        }

        if (!empty($tb_valid_thru))
        {
            $params['valid_thru'] = $tb_valid_thru;
        }
        if (!empty($tb_has_invoice))
        {
            $params['has_invoice'] = 'true';
        }
        if (!empty($tb_has_warranty))
        {
            $params['has_warranty'] = 'true';
        }
        if (!empty($tb_auto_repost))
        {
            $params['auto_repost'] = 'true';
        }
        if (!empty($tb_has_showcase))
        {
            $params['has_showcase'] = 'true';
        }
        if (!empty($tb_has_discount))
        {
            $params['has_discount'] = 'true';
        }
        if (!empty($tb_seller_code))
        {
            $params['outer_id'] = $tb_seller_code;
        }


        // 淘宝商品属性处理
        foreach ($_POST as $key => $val)
        {
            $key4 = substr($key, 0, 4);
            $key4l = substr($key, 4);
            if ($key4 == 'ppid' && !empty($val))
            {
                if (is_array($val))
                {
                    foreach ($val as $v)
                    {
                        $params['props'] .= $key4l . ':' . (strpos($v, '_') === 0 ? substr($v, 1) : $v) . ';';
                    }
                }
                else
                {
                    $params['props'] .= $key4l . ':' . (strpos($val, '_') === 0 ? substr($val, 1) : $val) . ';';
                }
            }
            elseif ($key4 == 'spid' && !empty($val))
            {
                if (is_array($val))
                {
                    $temp = array_unique($val);
                    foreach ($temp as $v)
                    {
                        $params['props'] .= $key4l . ':' . $v . ';';
                    }
                    foreach ($val as $v)
                    {
                        $sku_temp_arr[] = $key4l . ':' . $v;
                    }
                    $sku_temp[] = $sku_temp_arr;
                    unset($sku_temp_arr);
                }
            }
        }

        if (!empty($sku_temp))
        {
            for ($i=0; $i<count($sku_temp[0]); $i++)
            {
                for ($j=0; $j<count($sku_temp); $j++)
                {
                    $params['sku_properties'] .= $sku_temp[$j][$i] . ';';
                }
                $params['sku_properties'] = substr($params['sku_properties'] , 0, -1) . ',';
            }
        }


        if (!empty($params['sku_properties']))
        {
            $params['sku_properties'] = substr($params['sku_properties'], 0, -1);

            foreach ($_POST['tb_product_id'] as $key => $val)
            {
                $params['sku_outer_ids'] .= (empty($val) ? '' : $val) . ',';
            }
            $params['sku_outer_ids'] = substr($params['sku_outer_ids'], 0, -1);

            foreach ($_POST['tb_stock'] as $key => $val)
            {
                $params['sku_quantities'] .= (empty($val) ? 0 : $val) . ',';
            }
            $params['sku_quantities'] = substr($params['sku_quantities'], 0, -1);

            foreach ($_POST['tb_sale_price'] as $key => $val)
            {
                $params['sku_prices'] .= (empty($val) ? '0.00' : number_format($val, 2, '.', '')) . ',';
            }
            $params['sku_prices'] = substr($params['sku_prices'], 0, -1);
        }

        if (empty($_POST['tb_iid']))
        {
            $params['method'] = 'taobao.item.add';
        }
        else
        {
            $params['method'] = 'taobao.item.update';
            $params['iid'] = $_POST['tb_iid'];
        }

        $params = to_utf8_iconv($params);
        $tb_result = $taobao->testgetUserInfo($params,$tb_session,'GET');


        if (!empty($tb_result['item_add_response']) || !empty($tb_result['item_update_response']))
        {
            $tb_get_iid = empty($tb_result['item_add_response']) ? $tb_result['item_update_response'][0]['iid'] : $tb_result['item_add_response'][0]['iid'];

            //生成数据库语句，插入和更新同流程
            $tb_data['tb_goods_mount'] = $tb_goods_mount;
            $tb_data['tb_goods_price'] = $tb_goods_price;
            $tb_data['tb_auction_point'] = $tb_auction_point;
            $tb_data['tb_goods_from'] = $tb_goods_from;
            $tb_data['tb_goods_name'] = $tb_goods_name;
            $tb_data['tb_desc'] = $tb_desc;
            $tb_data['tb_goods_province'] = $tb_goods_province;
            $tb_data['tb_goods_city'] = $tb_goods_city;
            $tb_data['tb_pay_shipping'] = $tb_pay_shipping;
            $tb_data['tb_shipping_model'] = $tb_shipping_model;
            $tb_data['tb_shipping_normal'] = $params['post_fee'];
            $tb_data['tb_shipping_express'] = $params['express_fee'];
            $tb_data['tb_shipping_ems'] = $params['ems_fee'];
            $tb_data['tb_valid_thru'] = $tb_valid_thru;
            $tb_data['tb_has_invoice'] = $tb_has_invoice;
            $tb_data['tb_has_warranty'] = $tb_has_warranty;
            $tb_data['tb_auto_repost'] = $tb_auto_repost;
            $tb_data['tb_has_showcase'] = $tb_has_showcase;
            $tb_data['tb_has_discount'] = $tb_has_discount;
            $tb_data['tb_seller_code'] = $tb_seller_code;

            if (empty($org_cat_data))
            {
                $tb_data['tb_cid'] = '0_' . $_POST['tb_old_cid'];
            }
            else
            {
                $tb_data['tb_cid'] = $org_cat_data;
            }

            foreach ($_POST as $key => $val)
            {
                $key4 = substr($key, 0, 4);
                if (($key4 == 'ppid' || $key4 == 'spid') && !empty($val))
                {
                    $tb_data[$key] = (strpos($val, '_') === 0 ? substr($val, 1) : $val);
                }
            }

            if (!empty($_POST['tb_product_id']))
            {
                $tb_data['tb_product_id'] = $_POST['tb_product_id'];
            }
            if (!empty($_POST['tb_stock']))
            {
                $tb_data['tb_stock'] = $_POST['tb_stock'];
            }
            if (!empty($_POST['tb_sale_price']))
            {
                $tb_data['tb_sale_price'] = $_POST['tb_sale_price'];
            }

            $tb_data_str = serialize($tb_data);
            $db->query("UPDATE " . $ecs->table('goods') . " SET tb_iid = '$tb_get_iid', tb_data='$tb_data_str' WHERE goods_id='$goods_id'");

            if ((empty($_POST['tb_iid']) && (is_file(ROOT_PATH . $original_img) || is_file(ROOT_PATH . $tb_original_img))) or (!empty($_POST['tb_iid']) && is_file(ROOT_PATH . $original_img)))
            {
                unset($params);
                $params=$mess['result_msg'];
                $params['image'] = ROOT_PATH . (empty($original_img) ? $tb_original_img : $original_img);
                $params['iid'] = $tb_get_iid;
                $params['method'] = 'taobao.item.img.upload';
                $params['is_major'] = 'true';
                $params = to_utf8_iconv($params);

                $tb_result = $taobao->testgetUserInfo($params,$tb_session,'upload');
            }
        }
        else
        {
            //给出错误提示
            $tb_wrong = $tb_result['error_response']['msg'] . ' : ' . $tb_result['error_response']['sub_msg'];

            //echo '<pre>';print_r($params);echo '<pre>';print_r($tb_result);die();
        }
    }
}


/* 获取处理淘宝数据后产生的错误信息 */
function show_taobao_wrong()
{
    global $tb_wrong, $_LANG, $link;

    if (!empty($tb_wrong))
    {
        sys_msg($_LANG['tb_retry'] . $tb_wrong, 1, $link);
    }
}


/* 获取淘宝类目或商品属性 */
function get_tb_cats()
{
    global $_REQUEST, $tb_session, $taobao, $ecs, $db, $_LANG;

    $parent_cid = empty($_REQUEST['parentid']) ? 0 : substr($_REQUEST['parentid'], 2, (strpos($_REQUEST['parentid'], '|')-2));
    $is_parent = !empty($_REQUEST['inmemcatid']) ? 0 : (empty($_REQUEST['parentid']) ? 1 : substr($_REQUEST['parentid'], 0, 1));

    if ($is_parent)
    {
        $tb_cats = array();
        $session = $tb_session;

        if (empty($parent_cid))
        {
            $mess = $taobao->testgetUserInfo(array('method'=>'taobao.itemcats.authorize.get', 'fields'=>'brand.vid, brand.name, item_cat.cid, item_cat.name, item_cat.status,item_cat.sort_order,item_cat.parent_cid,item_cat.is_parent'),$session);
            $tb_cats = json_str_iconv($mess['itemcats_authorize_get_response']['seller_authorize']['item_cats']['item_cat']);
        }

        if (empty($tb_cats))
        {
            $mess = $taobao->testgetUserInfo(array('method'=>'taobao.itemcats.get', 'parent_cid'=>$parent_cid),$session);

            $tb_cats = json_str_iconv($mess['itemcats_get_response']['item_cats']['item_cat']);
        }
        $tb_cats_options = '';
        foreach ($tb_cats as $key => $val)
        {
            $tb_cats_options .= "<option value='" . (($val['is_parent'] == 'true') ? 1 : 0) . "_$val[cid]|$val[name]'>$val[name]</option>";
        }

        make_json_response($tb_cats_options, '', 'child');
    }
    else
    {
        if (!empty($_REQUEST['inmemcatid']))
        {
            $parent_cid = $_REQUEST['inmemcatid'];
            $sql = "SELECT tb_data FROM " . $ecs->table('goods') . " WHERE goods_id = '$_REQUEST[goods_id]'";
            $tb_goods_data = $db->getOne($sql);
            $tb_data_arr = unserialize($tb_goods_data);
        }

        $session = $tb_session;
        $mess = $taobao->testgetUserInfo(array('method'=>'taobao.itemprops.get','cid'=>$parent_cid, 'is_sale_prop'=>'false',  'fields'=>'pid, name, must, multi, prop_values, is_key_prop', 'is_sale_prop'=>'false', 'parent_pid'=>0),$tb_session);

        if (!empty($mess['itemprops_get_response']))
        {
            $tb_props = json_str_iconv($mess['itemprops_get_response']['item_props']['item_prop']);
            $normal_props_content = '';

            if (!empty($tb_props['prop_values']))
            {
                $tb_props = array($tb_props);
            }

            if (empty($tb_data_arr))
            {
                foreach ($tb_props as $key => $val)
                {
                    $normal_props_content .= "<tr><td class='label'>$val[name]</td><td>";
                    if (empty($val['prop_values']))
                    {
                        $normal_props_content .= "<input type='text' name='ppid$val[pid]'>";
                        $normal_props_content .= $val['must'] == 'true' ? $_LANG['require_field'] : '';
                        $normal_props_content .= '</td></tr>';
                    }
                    elseif ($val['multi'] == 'true')
                    {
                        foreach ($val['prop_values']['prop_value'] as $k => $v)
                        {
                            $normal_props_content .= "<input type='checkbox' name='ppid$val[pid][]' value='$v[vid]'> $v[name]";
                        }
                        $normal_props_content .= $val['must'] == 'true' ? $_LANG['require_field'] : '';
                        $normal_props_content .= '</td></tr>';
                    }
                    else
                    {
                        $has_child_prop = 0;
                        $temp_options_content = '';
                        foreach ($val['prop_values']['prop_value'] as $k => $v)
                        {
                            $temp_options_content .=  "<option value='";
                            if ($v['is_parent'] == 'true' && $val['is_key_prop'] == 'true' )
                            {
                                $temp_options_content .=  "_";
                                $has_child_prop = 1;
                            }
                            else
                            {
                                $temp_options_content .=  '';
                            }
                            $temp_options_content .=  "$v[vid]'> $v[name] </option>";

                        }
                        if (empty($has_child_prop))
                        {
                            $normal_props_content .= "<select name='ppid$val[pid]'><option value='0'> $_LANG[tb_choose_prop] </option>" . $temp_options_content . "</select>";
                        }
                        else
                        {
                            $child_div_pid = $val['pid'];
                            $normal_props_content .= "<select name='ppid$val[pid]' onchange='get_tb_child_cats(this)'><option value='0'> $_LANG[tb_choose_prop] </option>" . $temp_options_content . "</select><span id='childProp$val[pid]1'></span><span id='childProp$val[pid]2'></span><span id='childProp$val[pid]3'></span>";
                        }
                        $normal_props_content .= $val['must'] == 'true' ? $_LANG['require_field'] : '';
                        $normal_props_content .= '</td></tr>';
                    }
                }
            }
            else
            {
                foreach ($tb_props as $key => $val)
                {
                    $normal_props_content .= "<tr><td class='label'>$val[name]</td><td>";
                    if (empty($val['prop_values']))
                    {
                        $normal_props_content .= "<input type='text' name='ppid$val[pid]' value='" . (empty($tb_data_arr['ppid'.$val['pid']]) ? '' : $tb_data_arr['ppid'.$val['pid']]) . "'>";
                        $normal_props_content .= $val['must'] == 'true' ? $_LANG['require_field'] : '';
                        $normal_props_content .= '</td></tr>';
                    }
                    elseif ($val['multi'] == 'true')
                    {
                        foreach ($val['prop_values']['prop_value'] as $k => $v)
                        {
                            $temp_multi_props = empty($tb_data_arr['ppid'.$val['pid']]) ? '' : (is_array($tb_data_arr['ppid'.$val['pid']]) ? $tb_data_arr['ppid'.$val['pid']] : array($tb_data_arr['ppid'.$val['pid']]));
                            $normal_props_content .= "<input type='checkbox' name='ppid$val[pid][]' value='$v[vid]'" . ((!empty($temp_multi_props) && in_array($v['vid'], $temp_multi_props)) ? ' checked' : '') . "> $v[name]";
                        }
                        $normal_props_content .= $val['must'] == 'true' ? $_LANG['require_field'] : '';
                        $normal_props_content .= '</td></tr>';
                    }
                    else
                    {
                        $has_child_prop = 0;
                        $temp_options_content = '';
                        foreach ($val['prop_values']['prop_value'] as $k => $v)
                        {
                            $temp_options_content .=  "<option value='";
                            if ($v['is_parent'] == 'true')
                            {
                                $temp_options_content .=  "_";
                                $has_child_prop = 1;
                            }
                            else
                            {
                                $temp_options_content .=  '';
                            }
                            $temp_options_content .=  "$v[vid]'";
                            if (!empty($tb_data_arr['ppid'.$val['pid']]) && ($v['vid']==$tb_data_arr['ppid'.$val['pid']]))
                            {
                                $temp_options_content .=  " 'selected' ";
                            }
                            else
                            {
                                $temp_options_content .=  "";
                            }
                            $temp_options_content .=  "> $v[name] </option>";
                        }
                        if (empty($has_child_prop))
                        {
                            $normal_props_content .= "<select name='ppid$val[pid]'><option value='0'> $_LANG[tb_choose_prop] </option>" . $temp_options_content . "</select>";
                        }
                        else
                        {
                            $tb_child_cats_content = '';
                            if (!empty($tb_data_arr['ppid'.$val['pid']]))
                            {
                                unset($params);
                                $session = $tb_session;
                                $result = $taobao->testgetUserInfo(array('method'=>'taobao.products.search', 'fields'=> 'props', 'cid'=> $parent_cid, 'props'=>"{$val[pid]}:".$tb_data_arr['ppid'.$val['pid']]),$tb_session);

                                $products_search = json_str_iconv($result['products_search_response']['products']['product']);

                                if (empty($products_search))
                                {   //echo '<pre>';print_r($params);print_r($result);
                                    //如果搜索不到产品信息
                                }
                                else
                                {
                                    if ($products_search[0])
                                    {
                                        $products_search = $products_search[0];
                                    }
                                    $props_arr = explode(';', $products_search['props']);
                                    foreach ($props_arr as $pkey => $pval)
                                    {
                                        $prop_id = substr($pval, 0, strpos($pval, ':'));
                                        if ($maybe_prop_id != $val['pid'])
                                        {
                                            break;
                                        }
                                    }

                                    $result = $taobao->testgetUserInfo(array('method'=>'taobao.itempropvalues.get', 'fields'=> 'pid,prop_name,vid,name', 'cid'=> $parent_cid, 'pvs'=>"$prop_id"),$tb_session);

                                    $itempropvalues = json_str_iconv($result['itempropvalues_get_response']['prop_values']['prop_value']);

                                    if (empty($itempropvalues))
                                    {
                                        //如果没有获取到次关键属性
                                    }
                                    else
                                    {
                                        if (!empty($tb_postages['name']))
                                        {
                                            $itempropvalues = array($itempropvalues);
                                        }
                                        $tb_child_cats_content .= "&nbsp;&nbsp;{$itempropvalues[0][prop_name]} <select name='ppid{$itempropvalues[0][pid]}'><option value='0'> $_LANG[tb_choose_prop] </option>";

                                        foreach ($itempropvalues as $ckey => $cval)
                                        {
                                            $tb_child_cats_content .= "<option value='$cval[vid]'" . (($cval['vid'] == $tb_data_arr['ppid'.$prop_id]) ? 'selected' : '') . "> $cval[name] </option>";
                                        }

                                        $tb_child_cats_content .= "</select>";
                                    }
                                }
                            }

                            $child_div_pid = $val['pid'];
                            $normal_props_content .= "<select name='ppid$val[pid]' onchange='get_tb_child_cats(this)'><option value='0'> $_LANG[tb_choose_prop] </option>" . $temp_options_content . "</select><span id='childProp{$val[pid]}1'>&nbsp;&nbsp;{$tb_child_cats_content}</span><span id='childProp{$val[pid]}2'></span><span id='childProp{$val[pid]}3'></span>";
                        }
                        $normal_props_content .= $val['must'] == 'true' ? $_LANG['require_field'] : '';
                        $normal_props_content .= '</td></tr>';
                }
            }


            $normal_props_content .= '</table>';
            }
            $session = $tb_session;
            $mess = $taobao->testgetUserInfo(array('method'=>'taobao.itemprops.get', 'cid'=>$parent_cid, 'is_sale_prop'=>'true'),$tb_session);

            if (!empty($mess['itemprops_get_response']))
            {
                $tb_props = json_str_iconv($mess['itemprops_get_response']['item_props']['item_prop']);

                $normal_props_content .= '<table width="100%"><tr><td><h1>'.$_LANG['tb_sale_props'].'</h1></td></tr></table><table id="tb_sale_prop" width="100%"><tr><td></td><td>'.$_LANG['goods_sn'].'</td>';
                if (empty($tb_props['prop_values']))
                {
                    foreach ($tb_props as $key => $val)
                    {
                        $normal_props_content .= "<td>$val[name]</td>";
                    }
                }
                else
                {
                    $normal_props_content .= "<td>$tb_props[name]</td>";
                }

                $normal_props_content .= '<td>'.$_LANG['goods_number'].'</td><td>'.$_LANG['tb_sale_price'].'</td></tr>';

                $tb_props_num = 0;
                if (!empty($tb_data_arr))
                {
                    foreach ($tb_data_arr as $key => $val)
                    {
                        $sign_temp = substr($key, 0, 4);
                        if ($sign_temp == 'spid')
                        {
                            $tb_props_num = count($val);
                            break;
                        }
                    }
                }
                if (!empty($tb_props_num))
                {
                    for ($i=0; $i<$tb_props_num; $i++)
                    {
                        $normal_props_content .= '
                        <tr>
                        <td>'. (empty($i)?'<a href="javascript:;" onclick="addSaleProp(this)">[+]</a>':'<a href="javascript:;" onclick="removeSaleProp(this)">[-]</a>')
                        .'</td>
                        <td>
                           <input type="text" name="tb_product_id[]" value="' . (empty($tb_data_arr['tb_product_id'][$i]) ? '' : $tb_data_arr['tb_product_id'][$i]) . '">
                        </td>';
                        if (!empty($tb_props['prop_values']))
                        {
                            $tb_props = array($tb_props);
                        }
                        foreach ($tb_props as $key => $val)
                        {
                            $normal_props_content .= "<td><select name='spid$val[pid][]'><option value='0'> $_LANG[take_choose] </option>";

                            foreach ($val['prop_values']['prop_value'] as $k => $v)
                            {
                                $normal_props_content .= "<option value='$v[vid]' " . (($tb_data_arr['spid' . $val['pid']][$i] == $v['vid']) ? 'selected' : '') . "> $v[name] </option>";
                            }
                            $normal_props_content .= "</selcet></td>";
                        }

                        $normal_props_content .= '
                        <td>
                           <input type="text" name="tb_stock[]" value="' . (empty($tb_data_arr['tb_stock'][$i]) ? '' : $tb_data_arr['tb_stock'][$i]) . '">
                        </td>
                        <td>
                           <input type="text" name="tb_sale_price[]" value="' . (empty($tb_data_arr['tb_sale_price'][$i]) ? '' : $tb_data_arr['tb_sale_price'][$i]) . '">
                        </td>
                        </tr>';
                    }
                }
                else
                {
                    $normal_props_content .= '
                    <tr>
                    <td>
                       <a href="javascript:;" onclick="addSaleProp(this)">[+]</a>
                    </td>
                    <td>
                       <input type="text" name="tb_product_id[]">
                    </td>';
                    if (!empty($tb_props['prop_values']))
                    {
                        $tb_props = array($tb_props);
                    }
                    foreach ($tb_props as $key => $val)
                    {
                        $normal_props_content .= "<td><select name='spid$val[pid][]'><option value='0'> $_LANG[take_choose] </option>";

                        foreach ($val['prop_values']['prop_value'] as $k => $v)
                        {
                            $normal_props_content .= "<option value='$v[vid]'> $v[name] </option>";
                        }
                        $normal_props_content .= "</selcet></td>";
                    }

                    $normal_props_content .= '
                    <td>
                       <input type="text" name="tb_stock[]">
                    </td>
                    <td>
                       <input type="text" name="tb_sale_price[]">
                    </td>
                    </tr>';
                }
                $normal_props_content .= '</table>';
            }

            make_json_response($normal_props_content, '', 'prop');
        }
    }
}


/* 获取淘宝运费模板 */
function get_tb_postages()
{
    global $tb_session, $taobao, $_LANG, $_REQUEST;

    $session = $tb_session;
    $mess = $taobao->testgetUserInfo(array('method'=>'taobao.postages.get', 'fields'=>'postage_id,name'),$tb_session);

    $tb_postages = json_str_iconv($mess['postages_get_response']['postages']['postage']);
    $postages_content = '';

    if (empty($tb_postages))
    {
        $postages_content .= "<select name='tb_shipping_model'><option value='0'> $_LANG[tb_shipping_model_notice] </option></select>";
    }
    else
    {
        if (!empty($tb_postages['name']))
        {
            $tb_postages = array($tb_postages);
        }
        $postages_content .= "<select name='tb_shipping_model'><option value='0'> $_LANG[tb_choose_model] </option>";


        if (empty($_REQUEST['model']))
        {
            foreach ($tb_postages as $key => $val)
            {
                $postages_content .= "<option value='$val[postage_id]'> $val[name] </option>";
            }
        }
        else
        {
            foreach ($tb_postages as $key => $val)
            {
                $postages_content .= "<option value='$val[postage_id]' " . ($val['postage_id'] == $_REQUEST['model'] ? 'selected' : '') . "> $val[name] </option>";
            }
        }

        $postages_content .= "</select>";
    }
    make_json_result($postages_content);
}



/* 获取淘宝关键属性的子集属性 */
function get_tb_child_cats()
{
    global $_REQUEST, $taobao, $tb_session, $_LANG;

    $pid = substr($_REQUEST['pid'], 4);
    $vid = substr($_REQUEST['vid'], 1);
    $cid = intval($_REQUEST['cid']);

    $result = $taobao->testgetUserInfo(array('method'=>'taobao.products.search', 'fields'=> 'props', 'cid'=> $cid, 'props'=>"{$pid}:{$vid}"),$tb_session);

    $products_search = json_str_iconv($result['products_search_response']['products']['product']);

    if (!empty($products_search['props']))
    {
        $products_search = array($products_search);
    }

    if (empty($products_search))
    {   //echo '<pre>';print_r($params);print_r($result);
        //如果搜索不到产品信息
    }
    else
    {
        foreach ($products_search as $key => $val)
        {
            $props_arr = explode(';', $val['props']);

            foreach ($props_arr as $k => $v)
            {
                $prop_id = substr($v, 0, strpos($v, ':'));
                if ($prop_id != $pid)
                {
                    unset($params);
                    $itempropvalues = '';

                    $result = $taobao->testgetUserInfo(array('method'=>'taobao.itempropvalues.get', 'fields'=> 'pid,prop_name,vid,name', 'cid'=> $cid, 'pvs'=>"$prop_id"),$tb_session);

                    if (empty($result['itempropvalues_get_response']))
                    {
                        continue;
                    }
                    else
                    {
                        $itempropvalues = json_str_iconv($result['itempropvalues_get_response']['prop_values']['prop_value']);
                        break 2;
                    }
                }
            }
        }

        $itempropvalues = empty($result['itempropvalues_get_response']) ? '' : json_str_iconv($result['itempropvalues_get_response']['prop_values']['prop_value']);
        $tb_child_cats_content = '';

        if (empty($itempropvalues))
        {
            //如果没有获取到次关键属性
        }
        else
        {
            if (!empty($itempropvalues['name']))
            {
                $itempropvalues = array($itempropvalues);
            }
            $tb_child_cats_content .= "&nbsp;&nbsp;{$itempropvalues[0][prop_name]} <select name='ppid{$itempropvalues[0][pid]}'><option value='0'> $_LANG[tb_choose_prop] </option>";

            foreach ($itempropvalues as $key => $val)
            {
                $tb_child_cats_content .= "<option value='$val[vid]'> $val[name] </option>";
            }

            $tb_child_cats_content .= "</select>";
        }
        make_json_result($tb_child_cats_content);
    }
}


/**
 * 取得订单信息
 * @param   int     $order_id   订单id（如果order_id > 0 就按id查，否则按sn查）
 * @param   string  $order_sn   订单号
 * @return  array   订单信息（金额都有相应格式化的字段，前缀是formated_）
 */
function taobao_order($order_id, $order_sn = '')
{
    /* 计算订单各种费用之和的语句 */
    $total_fee = " (goods_amount - discount + tax + shipping_fee + insure_fee + pay_fee + pack_fee + card_fee) AS total_fee ";
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = "SELECT *, " . $total_fee . " FROM " . $GLOBALS['ecs']->table('taobao_order') .
                " WHERE order_id = '$order_id'";
    }
    else
    {
        $sql = "SELECT *, " . $total_fee . "  FROM " . $GLOBALS['ecs']->table('taobao_order') .
                " WHERE order_sn = '$order_sn'";
    }
    $order = $GLOBALS['db']->getRow($sql);

    /* 格式化金额字段 */
    if ($order)
    {
        $order['formated_goods_amount']   = price_format($order['goods_amount'], false);
        $order['formated_discount']       = price_format($order['discount'], false);
        $order['formated_tax']            = price_format($order['tax'], false);
        $order['formated_shipping_fee']   = price_format($order['shipping_fee'], false);
        $order['formated_insure_fee']     = price_format($order['insure_fee'], false);
        $order['formated_pay_fee']        = price_format($order['pay_fee'], false);
        $order['formated_pack_fee']       = price_format($order['pack_fee'], false);
        $order['formated_card_fee']       = price_format($order['card_fee'], false);
        $order['formated_total_fee']      = price_format($order['total_fee'], false);
        $order['formated_money_paid']     = price_format($order['money_paid'], false);
        $order['formated_bonus']          = price_format($order['bonus'], false);
        $order['formated_integral_money'] = price_format($order['integral_money'], false);
        $order['formated_surplus']        = price_format($order['surplus'], false);
        $order['formated_order_amount']   = price_format(abs($order['order_amount']), false);
        $order['formated_add_time']       = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);
    }

    return $order;
}


/**
 *  获取淘宝订单列表信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function taobao_order_list()
{
    $result = get_filter();
    if ($result === false)
    {

        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }

        /* 记录总数 */
        if ($filter['user_name'])
        {
            $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('taobao_order') . " AS o ,".
                   $GLOBALS['ecs']->table('users') . " AS u " . $where;
        }
        else
        {
            $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('taobao_order') . " AS o ". $where;
        }

        $filter['record_count']   = $GLOBALS['db']->getOne($sql);
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;

        /* 查询 */
        $sql = "SELECT *".
                " FROM " . $GLOBALS['ecs']->table('taobao_order') .
                " ORDER BY `add_time` desc ".
                " LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";

        foreach (array('order_sn', 'consignee', 'email', 'address', 'zipcode', 'tel', 'user_name') AS $val)
        {
            $filter[$val] = stripslashes($filter[$val]);
        }
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $row = $GLOBALS['db']->getAll($sql);

    /* 格式话数据 */
    foreach ($row AS $key => $value)
    {
        $row[$key]['formated_order_amount'] = price_format($value['order_amount']);
        $row[$key]['formated_money_paid'] = price_format($value['money_paid']);
        $row[$key]['formated_total_fee'] = price_format($value['total_fee']);

        if ($value['order_status'] == OS_INVALID || $value['order_status'] == OS_CANCELED)
        {
            /* 如果该订单为无效或取消则显示删除链接 */
            $row[$key]['can_remove'] = 1;
        }
        else
        {
            $row[$key]['can_remove'] = 0;
        }
    }
    $arr = array('orders' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

    return $arr;
}


/* 淘宝订单列表 */
function taobao_list()
{
    global $ecs, $db, $_LANG, $smarty;

    $smarty->path = ROOT_PATH . 'includes/modules/taobao/themes/';

    $sql = "SELECT value FROM " . $ecs->table('shop_config') . "WHERE id = 299";
    $taobao_config = $db->getOne($sql);
    if(!$taobao_config)
    {
        echo $_LANG['config_taobao'];
        exit;
    }

    /* 模板赋值 */
    $smarty->assign('ur_here', $_LANG['11_taobao_list']);
    $smarty->assign('action_link', array('href' => 'order.php?act=taobao_import', 'text' => $_LANG['12_taobao_list']));


    $smarty->assign('full_page',        1);

    $order_list = taobao_order_list();
    $smarty->assign('order_list',   $order_list['orders']);
    $smarty->assign('filter',       $order_list['filter']);
    $smarty->assign('record_count', $order_list['record_count']);
    $smarty->assign('page_count',   $order_list['page_count']);
    $smarty->assign('sort_order_time', '<img src="images/sort_desc.gif">');

    /* 显示模板 */
    assign_query_info();
    $smarty->display('taobao_list.htm');
}


/* 淘宝确认发货 */
function taobao_close()
{
    global $taobao, $_REQUEST, $tb_session;

    $mess = $taobao->testgetUserInfo(array('method'=>'taobao.delivery.send','tid'=>$_REQUEST['order_sn'],'order_type'=>'virtual_goods'),$tb_session);

    if(empty($mess['error_response']))
    {
        $status = 'WAIT_BUYER_CONFIRM_GOODS';
        $minus_stock_sql = "UPDATE " . $GLOBALS['ecs']->table('taobao_order') . "
                        SET order_status = '" . $_LANG[$status] . "',chick_status = '".$status."', shipping_time ='" .date("Y-m-d H:i:s") ."'
                        WHERE `order_sn` = " . $_REQUEST['order_sn'];

        $GLOBALS['db']->query($minus_stock_sql, 'SILENT');

    }
    ecs_header("Location: order.php?act=taobao_list\n");
}


/* 淘宝评论 */
function taobao_rate()
{
    global $_REQUEST, $taobao, $tb_session, $smarty;

    $smarty->path = ROOT_PATH . 'includes/modules/taobao/admin/';

    if($_REQUEST['ra'])
    {
        $rate_msg = (EC_CHARSET != 'utf-8') ? ecs_iconv('gbk','UTF8',$_REQUEST['rate_msg']) : $_REQUEST['rate_msg'];

        $mess = $taobao->testgetUserInfo(array('method'=>'taobao.traderate.list.add','tid'=>$_REQUEST['order_sn'],'result'=>$_REQUEST['rate'],'role'=>'seller','content'=>$rate_msg,'anony'=>'false'),$tb_session,'POST');

        if(empty($mess['error_response']))
        {
            $status = 'WAIT_BUYER_CONFIRM_GOODS';
            $minus_stock_sql = "UPDATE " . $GLOBALS['ecs']->table('taobao_order') . "
                            SET seller_rate = 'true'
                            WHERE `order_sn` = " . $_REQUEST['order_sn'];

            $GLOBALS['db']->query($minus_stock_sql, 'SILENT');

        }

        ecs_header("Location: order.php?act=taobao_list\n");
    }
    else
    {
        $smarty->assign('order_sn',   $_REQUEST['order_sn']);
        $smarty->display('taobao_rate.htm');
    }
}


/* 淘宝数据导入 */
function taobao_import()
{
    global $taobao, $tb_session, $db, $ecs, $_REQUEST, $_CFG;

    set_time_limit(0);

    $page_size = 10;
    $page = empty($_REQUEST['page']) ? 1 : $_REQUEST['page'];

    /* 获取合适的订单。
       根据上次更新时间来获取：订单的创建时间和结束时间落在上次更新和当前时间之间的。同时更新最后更新时间
       如果没有上次更新时间，获取所有的订单，并设置上次更新时间。
    */
    if (empty($_CFG['taobao_last_update']))
    {
        $start_created  = '';
        $end_created = '';
    }
    else
    {
        $date_str = local_date('Y-m-d G:i:s', $_CFG['taobao_last_update']);
        $start_created  = $date_str;
        $end_created = $date_str;
    }

    $mess = $taobao->testgetUserInfo(array('method'=>'taobao.trades.sold.get','fields'=>'seller_nick, buyer_nick, title, type, created, sid, tid, seller_rate, buyer_rate, status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, pic_path, iid, num, price, cod_fee, cod_status, shipping_type, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone', 'page_no'=>$page, 'page_size'=>$page_size, 'start_created'=>$start_created, 'end_created'=>$end_created),$tb_session);//测试获取淘宝的用户信息

    $page++;

    if (!empty($mess['trades_sold_get_response']['trades']['trade']))
    {
        foreach ($mess['trades_sold_get_response']['trades']['trade'] as $va )
        {
            $adjust_fee = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['adjust_fee']) : $va['adjust_fee'];//卖家优惠金额.格式为:1.01;单位:元;精确到小数点后两位.
            $buyer_nick = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['buyer_nick']) : $va['buyer_nick'];//买家昵称

            $buyer_rate = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['buyer_rate']) : $va['buyer_rate'];// 买家是否已评价。可选值:true(已评价),false(未评价)
        //    $cod_fee = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['cod_fee']) : $va['cod_fee'];// 0.00 货到付款服务费。精确到2位小数;单位:元。如:12.07，表示:12元7分
        //    $cod_status = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['cod_status']) : $va['cod_status'];// 货到付款物流状态
            $consign_time = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['consign_time']) : $va['consign_time'];//卖家发货时间。格式:yyyy-MM-dd HH:mm:ss
            $created = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['created']) : $va['created'];//交易创建时间。格式:yyyy-MM-dd HH:mm:ss

            $iid = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['iid']) : $va['iid'];//商品字符串编号

            $num = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['num']) : $va['num'];//
            $pay_time = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['pay_time']) : $va['pay_time'];//付款时间。格式:yyyy-MM-dd HH:mm:ss
            $payment = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['payment']) : $va['payment'];//买家实付金额（包含物流费用）。精确到2位小数，单位:元。如:200.07，表示:200元7分

        //    $post_fee = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['post_fee']) : $va['post_fee'];// 邮费。精确到2位小数;单位:元。如:200.07，表示:200元7分
            $price = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['price']) : $va['price'];// 商品价格。精确到2位小数；单位：元。如：200.07，表示：200元7分

        //    $received_payment = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['received_payment']) : $va['received_payment'];//卖家实际收到的支付宝打款金额。精确到2位小数;单位:元。如:200.07，表示:200元7
            $receiver_address = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['receiver_address']) : $va['receiver_address'];//丹棱街16号海兴大厦C座1110 收货人的详细地址
            $receiver_city = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['receiver_city']) : $va['receiver_city'];// 北京市 收货人的所在城市
            $receiver_district = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['receiver_district']) : $va['receiver_district'];// 海淀区 收货人的所在地区
            $receiver_mobile = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['receiver_mobile']) : $va['receiver_mobile'];// 13601203954 收货人的手机号码
            $receiver_name = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['receiver_name']) : $va['receiver_name'];// 石潇川 收货人的姓名
            $receiver_state = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['receiver_state']) : $va['receiver_state'];// 北京 收货人的所在省份
            $receiver_zip = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['receiver_zip']) : $va['receiver_zip'];//100080 收货人的邮编

            $seller_rate = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['seller_rate']) : $va['seller_rate'];// 卖家是否已评价。可选值:true(已评价),false(未评价)
            $shipping_type = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['shipping_type']) : $va['shipping_type'];// 创建交易时的物流方式（交易完成前，物流方式有可能改变，但系统里的这个字段一直不变）
        //    $sid = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['sid']) : $va['sid'];// 34589627101979
            $status = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['status']) : $va['status'];// 交易状态
            $tid = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['tid']) : $va['tid'];//34589627101979 交易编号 (父订单的交易编号)
        //    $total_fee = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['total_fee']) : $va['total_fee'];//0.01 商品金额。精确到2位小数;单位:元。如:200.07，表示:200元7分
            $type = (EC_CHARSET != 'utf-8') ? ecs_iconv('UTF8','gbk',$va['type']) : $va['type'];$va[type];//fixed 交易类型

            $sql = "SELECT order_sn FROM " . $ecs->table('taobao_order') . " WHERE order_sn = '$tid'";

            $agency_id = $db->getOne($sql);


            $order = array(
                'adjust_fee'      => $adjust_fee,
                'buyer_nick'      => $buyer_nick,
                'buyer_rate'      => $buyer_rate,
    //                    'cod_fee'         => $cod_fee,
    //                    'order_sn'        => $cod_status,
                'shipping_time'   => $consign_time,
                'add_time'        => $created,
                'order_iid'       => $iid,
                'goods_num'       => $num,
                'pay_time'        => $pay_time,
                'money_paid'      => $payment,
    //                    'seller_type'     => $post_fee,
                'goods_amoun'     => $price,
                'total_fee'       => $payment,
    //                    'seller_type'     => $received_payment,
                'address'         => $receiver_address,
                'city'            => $receiver_city,
                'district'        => $receiver_district,
                'mobile'          => $receiver_mobile,
                'user_name'       => $receiver_name,
                'province'        => $receiver_state,
                'zipcode'         => $receiver_zip,
                'seller_rate'     => $seller_rate,
                'shipping_name'   => $shipping_type,
    //                    'seller_type'     => $sid,
                'order_status'    => $_LANG[$status],
                'chick_status'    => $status,
                'order_sn'        => $tid,
    //                    'seller_type'     => $total_fee,
                'seller_type'     => $type
            );

            if (empty($agency_id))
            {
                    $db->autoExecute($ecs->table('taobao_order'), $order, 'INSERT', '', 'SILENT');
                    if ($error_no > 0 && $error_no != 1062)
                    {
                        die($GLOBALS['db']->errorMsg());
                    }

            }
            else
            {
                $db->autoExecute($ecs->table('taobao_order'), $order, 'UPDATE', '`order_sn`='.$tid, 'SILENT');
                    if ($error_no > 0 && $error_no != 1062)
                    {
                        die($GLOBALS['db']->errorMsg());
                    }

            }
        }

        //继续分批处理，下一页
        ecs_header("Location: order.php?act=taobao_import&page=" . $page);
        exit;
    }

    if (empty($_CFG['taobao_last_update']))
    {
        $db->query('INSERT INTO ' . $ecs->table('shop_config') . ' (id, parent_id, code, type, value) VALUES ("297", "2", "taobao_last_update", "hidden", "' . gmtime() . '")');
    }
    else
    {
        $db->query('UPDATE ' . $ecs->table('shop_config') . ' SET value = "' . gmtime(). '" WHERE code = "taobao_last_update"');
    }
    clear_all_files();
    ecs_header("Location: order.php?act=taobao_list\n");
    exit;
}


/* 淘宝订单详情页面 */
function taobao_info()
{
    global $_REQUEST, $ecs, $db, $smarty, $_LANG, $_GET, $_CFG;

    $smarty->path = ROOT_PATH . 'includes/modules/taobao/themes/';

    /* 根据订单id或订单号查询订单信息 */
    if (isset($_REQUEST['order_id']))
    {
        $order_id = intval($_REQUEST['order_id']);
        $order = taobao_order($order_id);
    }
    elseif (isset($_REQUEST['order_sn']))
    {
        $order_sn = trim($_REQUEST['order_sn']);
        $order = taobao_order(0, $order_sn);
    }
    else
    {
        /* 如果参数不存在，退出 */
        die('invalid parameter');
    }

    /* 如果订单不存在，退出 */
    if (empty($order))
    {
        die('order does not exist');
    }

    /* 根据订单是否完成检查权限 */
    if (order_finished($order))
    {
        admin_priv('order_view_finished');
    }
    else
    {
        admin_priv('order_view');
    }



    /* 取得上一个、下一个订单号 */
    if (!empty($_COOKIE['ECSCP']['lastfilter']))
    {
        $filter = unserialize(urldecode($_COOKIE['ECSCP']['lastfilter']));
        if (!empty($filter['composite_status']))
        {
            $where = '';
            //综合状态
            switch($filter['composite_status'])
            {
                case CS_AWAIT_PAY :
                    $where .= order_query_sql('await_pay');
                    break;

                case CS_AWAIT_SHIP :
                    $where .= order_query_sql('await_ship');
                    break;

                case CS_FINISHED :
                    $where .= order_query_sql('finished');
                    break;

                default:
                    if ($filter['composite_status'] != -1)
                    {
                        $where .= " AND o.order_status = '$filter[composite_status]' ";
                    }
            }
        }
    }
    $sql = "SELECT MAX(order_id) FROM " . $ecs->table('taobao_order') . " as o WHERE order_id < '$order[order_id]'";
    if ($agency_id > 0)
    {
        $sql .= " AND agency_id = '$agency_id'";
    }
    if (!empty($where))
    {
        $sql .= $where;
    }
    $smarty->assign('prev_id', $db->getOne($sql));
    $sql = "SELECT MIN(order_id) FROM " . $ecs->table('taobao_order') . " as o WHERE order_id > '$order[order_id]'";
    if ($agency_id > 0)
    {
        $sql .= " AND agency_id = '$agency_id'";
    }
    if (!empty($where))
    {
        $sql .= $where;
    }
    $smarty->assign('next_id', $db->getOne($sql));





    /* 格式化金额 */
    if ($order['order_amount'] < 0)
    {
        $order['money_refund']          = abs($order['order_amount']);
        $order['formated_money_refund'] = price_format(abs($order['order_amount']));
    }



    /* 取得订单的来源 */
    $order['referer'] = $_LANG['taobao'];


    /* 此订单的发货备注(此订单的最后一条操作记录) */
    $sql = "SELECT action_note FROM " . $ecs->table('order_action').
           " WHERE order_id = '$order[order_id]' AND shipping_status = 1 ORDER BY log_time DESC";
    $order['invoice_note'] = $db->getOne($sql);

    /* 取得订单商品总重量 */
    $weight_price = order_weight_price($order['order_id']);
    $order['total_weight'] = $weight_price['formated_weight'];

    /* 参数赋值：订单 */
    $smarty->assign('order', $order);


    /* 取得订单商品及货品 */
    $goods_list = array();
    $goods_attr = array();
    $sql = "SELECT o.*, IF(o.product_id > 0, p.product_number, g.goods_number) AS storage, o.goods_attr, g.suppliers_id, IFNULL(b.brand_name, '') AS brand_name, p.product_sn
            FROM " . $ecs->table('order_goods') . " AS o
                LEFT JOIN " . $ecs->table('products') . " AS p
                    ON p.product_id = o.product_id
                LEFT JOIN " . $ecs->table('goods') . " AS g
                    ON o.goods_id = g.goods_id
                LEFT JOIN " . $ecs->table('brand') . " AS b
                    ON g.brand_id = b.brand_id
            WHERE o.order_id = '$order[order_id]'";
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res))
    {
        /* 虚拟商品支持 */
        if ($row['is_real'] == 0)
        {
            /* 取得语言项 */
            $filename = ROOT_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $_CFG['lang'] . '.php';
            if (file_exists($filename))
            {
                include_once($filename);
                if (!empty($_LANG[$row['extension_code'].'_link']))
                {
                    $row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
                }
            }
        }

        $row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
        $row['formated_goods_price']    = price_format($row['goods_price']);

        $goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组

        if ($row['extension_code'] == 'package_buy')
        {
            $row['storage'] = '';
            $row['brand_name'] = '';
            $row['package_goods_list'] = get_package_goods($row['goods_id']);
        }

        $goods_list[] = $row;
    }

    $attr = array();
    $arr  = array();
    foreach ($goods_attr AS $index => $array_val)
    {
        foreach ($array_val AS $value)
        {
            $arr = explode(':', $value);//以 : 号将属性拆开
            $attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
        }
    }

    $smarty->assign('goods_attr', $attr);
    $smarty->assign('goods_list', $goods_list);

    /* 取得能执行的操作列表 */
    $operable_list = operable_list($order);
    $smarty->assign('operable_list', $operable_list);

    /* 取得订单操作记录 */
    $act_list = array();
    $sql = "SELECT * FROM " . $ecs->table('order_action') . " WHERE order_id = '$order[order_id]' ORDER BY log_time DESC,action_id DESC";
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res))
    {
        $row['order_status']    = $_LANG['os'][$row['order_status']];
        $row['pay_status']      = $_LANG['ps'][$row['pay_status']];
        $row['shipping_status'] = $_LANG['ss'][$row['shipping_status']];
        $row['action_time']     = local_date($_CFG['time_format'], $row['log_time']);
        $act_list[] = $row;
    }
    $smarty->assign('action_list', $act_list);

    /* 取得是否存在实体商品 */
    $smarty->assign('exist_real_goods', exist_real_goods($order['order_id']));

    /* 是否打印订单，分别赋值 */
    if (isset($_GET['print']))
    {
        $smarty->assign('shop_name',    $_CFG['shop_name']);
        $smarty->assign('shop_url',     $ecs->url());
        $smarty->assign('shop_address', $_CFG['shop_address']);
        $smarty->assign('service_phone',$_CFG['service_phone']);
        $smarty->assign('print_time',   local_date($_CFG['time_format']));
        $smarty->assign('action_user',  $_SESSION['admin_name']);

        $smarty->template_dir = '../' . DATA_DIR;
        $smarty->display('order_print.html');
    }
    /* 打印快递单 */
    elseif (isset($_GET['shipping_print']))
    {
        //$smarty->assign('print_time',   local_date($_CFG['time_format']));
        //发货地址所在地
        $region_array = array();
        $region_id = !empty($_CFG['shop_country']) ? $_CFG['shop_country'] . ',' : '';
        $region_id .= !empty($_CFG['shop_province']) ? $_CFG['shop_province'] . ',' : '';
        $region_id .= !empty($_CFG['shop_city']) ? $_CFG['shop_city'] . ',' : '';
        $region_id = substr($region_id, 0, -1);
        $region = $db->getAll("SELECT region_id, region_name FROM " . $ecs->table("region") . " WHERE region_id IN ($region_id)");
        if (!empty($region))
        {
            foreach($region as $region_data)
            {
                $region_array[$region_data['region_id']] = $region_data['region_name'];
            }
        }
        $smarty->assign('shop_name',    $_CFG['shop_name']);
        $smarty->assign('order_id',    $order_id);
        $smarty->assign('province', $region_array[$_CFG['shop_province']]);
        $smarty->assign('city', $region_array[$_CFG['shop_city']]);
        $smarty->assign('shop_address', $_CFG['shop_address']);
        $smarty->assign('service_phone',$_CFG['service_phone']);
        $shipping = $db->getRow("SELECT * FROM " . $ecs->table("shipping") . " WHERE shipping_id = " . $order['shipping_id']);

        //打印单模式
        if ($shipping['print_model'] == 2)
        {
            /* 可视化 */
            /* 快递单 */
            $shipping['print_bg'] = empty($shipping['print_bg']) ? '' : get_site_root_url() . $shipping['print_bg'];

            /* 取快递单背景宽高 */
            if (!empty($shipping['print_bg']))
            {
                $_size = @getimagesize($shipping['print_bg']);

                if ($_size != false)
                {
                    $shipping['print_bg_size'] = array('width' => $_size[0], 'height' => $_size[1]);
                }
            }

            if (empty($shipping['print_bg_size']))
            {
                $shipping['print_bg_size'] = array('width' => '1024', 'height' => '600');
            }

            /* 标签信息 */
            $lable_box = array();
            $lable_box['t_shop_country'] = $region_array[$_CFG['shop_country']]; //网店-国家
            $lable_box['t_shop_city'] = $region_array[$_CFG['shop_city']]; //网店-城市
            $lable_box['t_shop_province'] = $region_array[$_CFG['shop_province']]; //网店-省份
            $lable_box['t_shop_name'] = $_CFG['shop_name']; //网店-名称
            $lable_box['t_shop_district'] = ''; //网店-区/县
            $lable_box['t_shop_tel'] = $_CFG['service_phone']; //网店-联系电话
            $lable_box['t_shop_address'] = $_CFG['shop_address']; //网店-地址
            $lable_box['t_customer_country'] = $region_array[$order['country']]; //收件人-国家
            $lable_box['t_customer_province'] = $region_array[$order['province']]; //收件人-省份
            $lable_box['t_customer_city'] = $region_array[$order['city']]; //收件人-城市
            $lable_box['t_customer_district'] = $region_array[$order['district']]; //收件人-区/县
            $lable_box['t_customer_tel'] = $order['tel']; //收件人-电话
            $lable_box['t_customer_mobel'] = $order['mobile']; //收件人-手机
            $lable_box['t_customer_post'] = $order['zipcode']; //收件人-邮编
            $lable_box['t_customer_address'] = $order['address']; //收件人-详细地址
            $lable_box['t_customer_name'] = $order['user_name']; //收件人-姓名

            $gmtime_utc_temp = gmtime(); //获取 UTC 时间戳
            $lable_box['t_year'] = date('Y', $gmtime_utc_temp); //年-当日日期
            $lable_box['t_months'] = date('m', $gmtime_utc_temp); //月-当日日期
            $lable_box['t_day'] = date('d', $gmtime_utc_temp); //日-当日日期

            $lable_box['t_order_no'] = $order['order_sn']; //订单号-订单
            $lable_box['t_order_postscript'] = $order['postscript']; //备注-订单
            $lable_box['t_order_best_time'] = $order['best_time']; //送货时间-订单
            $lable_box['t_pigeon'] = '√'; //√-对号
            $lable_box['t_custom_content'] = ''; //自定义内容

            //标签替换
            $temp_config_lable = explode('||,||', $shipping['config_lable']);
            if (!is_array($temp_config_lable))
            {
                $temp_config_lable[] = $shipping['config_lable'];
            }
            foreach ($temp_config_lable as $temp_key => $temp_lable)
            {
                $temp_info = explode(',', $temp_lable);
                if (is_array($temp_info))
                {
                    $temp_info[1] = $lable_box[$temp_info[0]];
                }
                $temp_config_lable[$temp_key] = implode(',', $temp_info);
            }
            $shipping['config_lable'] = implode('||,||',  $temp_config_lable);

            $smarty->assign('shipping', $shipping);

            $smarty->display('print.htm');
        }
        elseif (!empty($shipping['shipping_print']))
        {
            /* 代码 */
            echo $smarty->fetch("str:" . $shipping['shipping_print']);
        }
        else
        {
            $shipping_code = $db->getOne("SELECT shipping_code FROM " . $ecs->table('shipping') . " WHERE shipping_id=" . $order['shipping_id']);
            include_once(ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php');
            if (!empty($_LANG['shipping_print']))
            {
                echo $smarty->fetch("str:$_LANG[shipping_print]");
            }
            else
            {
                echo $_LANG['no_print_shipping'];
            }
        }
    }
    else
    {
        /* 模板赋值 */
        $smarty->assign('ur_here', $_LANG['order_info']);
        $smarty->assign('action_link', array('href' => 'order.php?act=taobao_list', 'text' => $_LANG['11_taobao_list']));

        /* 显示模板 */
        assign_query_info();
        $smarty->display('taobao_order_info.htm');
    }
}


/* 下载当前用户所有商品到本地 */
function get_taobao_goods()
{
    global $tb_session, $taobao, $ecs, $db, $_LANG, $_CFG, $_REQUEST, $smarty;

    set_time_limit(0);

    $page_size = empty($_REQUEST['pagesize']) ? 10 : $_REQUEST['pagesize'];
    $page = empty($_REQUEST['page']) ? 1 : $_REQUEST['page'];

    $mess = $taobao->testgetUserInfo(array('method'=>'taobao.items.all.get', 'fields'=>'iid', 'page_no'=>$page, 'page_size'=>$page_size),$tb_session);

    $page++;

    $tb_goods_list = json_str_iconv($mess['items_all_get_response']);
    if (empty($tb_goods_list))
    {
        $smarty->assign('down_ok', 1);
    }
    else
    {
        $tb_goods = $tb_goods_list['items'];
        $tb_goods_count = $tb_goods_list['total_results'];

        if (!empty($tb_goods['iid']))
        {
            $tb_goods = array($tb_goods);
        }

        if (!empty($tb_goods))
        {
            $tb_goods_info = array();
            foreach ($tb_goods as $key => $val)
            {
                $mess = '';
                $mess = $taobao->testgetUserInfo(array('method'=>'taobao.item.get', 'fields'=>'iid, title, cid, props, desc, num, valid_thru, list_time, stuff_status, location, price, post_fee, express_fee, ems_fee, has_discount, freight_payer, has_invoice, has_warranty, has_showcase, auto_repost, approve_status, postage_id, product_id, sku.price, sku.outer_id, sku.properties, sku.quantity, outer_id', 'nick'=>to_utf8_iconv($_CFG['taobao_account']), 'iid'=>$val['iid']),$tb_session);

                $tb_good_info = json_str_iconv($mess['item_get_response'][0]);
                $tb_goods_info[] = $tb_good_info;
            }

            $goods_query_info = '';
            $tb_goods_info = addslashes_deep($tb_goods_info);
            foreach ($tb_goods_info as $key => $val)
            {
                $good_info = array();
                $good_info['goods_name'] = $val['title'];
                $good_info['shop_price'] = $val['price'];
                $good_info['goods_desc'] = $val['desc'];
                $good_info['tb_iid'] = $val['iid'];


                $tb_data = array();
                $tb_data['tb_goods_mount'] = $val['num'];
                $tb_data['tb_goods_price'] = $val['price'];
                $tb_data['tb_goods_from'] = $val['stuff_status'];
                $tb_data['tb_goods_name'] = $val['title'];
                $tb_data['tb_desc'] = $val['desc'];
                $tb_data['tb_goods_province'] = $val['location']['state'];
                $tb_data['tb_goods_city'] = $val['location']['city'];
                $tb_data['tb_pay_shipping'] = ($val['freight_payer'] == 'buyer') ? 1 : 2;
                $tb_data['tb_shipping_model'] = $val['postage_id'];
                $tb_data['tb_shipping_normal'] = $val['post_fee'];
                $tb_data['tb_shipping_express'] = $val['express_fee'];
                $tb_data['tb_shipping_ems'] = $val['ems_fee'];
                $tb_data['tb_valid_thru'] = $val['valid_thru'];
                $tb_data['tb_has_invoice'] = ($val['has_invoice'] == 'true') ? 1 : '';
                $tb_data['tb_has_warranty'] = ($val['has_warranty'] == 'true') ? 1 : '';
                $tb_data['tb_auto_repost'] = ($val['auto_repost'] == 'true') ? 1 : '';
                $tb_data['tb_has_showcase'] = ($val['has_showcase'] == 'true') ? 1 : '';
                $tb_data['tb_has_discount'] = ($val['has_discount'] == 'true') ? 1 : '';
                $tb_data['tb_seller_code'] = $val['outer_id'];
                $tb_data['tb_cid'] = '0_' . $val['cid'];

                $sku_props = array();

                if (!empty($val['skus']['sku']))
                {
                    $temp_tb_data = $val['skus']['sku'];
                    if (!empty($temp_tb_data['properties']))
                    {
                        $temp_tb_data = array($temp_tb_data);
                    }

                    $tb_data['tb_product_id'] = array();
                    $tb_data['tb_stock'] = array();
                    $tb_data['tb_sale_price'] = array();

                    foreach ($temp_tb_data as $tkey => $tval)
                    {
                        $tb_data['tb_product_id'][] = empty($tval['outer_id']) ? '' : $tval['outer_id'];
                        $tb_data['tb_stock'][] = empty($tval['quantity']) ? '' : $tval['quantity'];
                        $tb_data['tb_sale_price'][] = empty($tval['price']) ? '' : $tval['price'];

                        $properties_temp_arr = explode(';', $tval['properties']);
                        foreach ($properties_temp_arr as $pk => $pv)
                        {
                            $propertie_temp_arr = explode(':', $pv);
                            $tb_data['spid' . $propertie_temp_arr[0]][] = $propertie_temp_arr[1];

                            if (empty($sku_props))
                            {
                                $sku_props[] = $propertie_temp_arr[0];
                            }
                        }
                    }
                }

                if (!empty($val['props']))
                {
                    $temp_props_arr = explode(';', $val['props']);
                    foreach ($temp_props_arr as $pkey => $pval)
                    {
                          $temp_prop_arr = explode(':', $pval);
                          if (!in_array($temp_prop_arr[0], $sku_props))
                          {
                              if (empty($tb_data['ppid' . $temp_prop_arr[0]]))
                              {
                                  $tb_data['ppid' . $temp_prop_arr[0]]= $temp_prop_arr[1];
                              }
                              else
                              {
                                  if (is_array($tb_data['ppid' . $temp_prop_arr[0]]))
                                  {
                                      $tb_data['ppid' . $temp_prop_arr[0]][] = $temp_prop_arr[1];
                                  }
                                  else
                                  {
                                      $tb_data['ppid' . $temp_prop_arr[0]] = array($temp_prop_arr[1], $tb_data['ppid' . $temp_prop_arr[0]]);
                                  }
                              }
                          }
                    }
                }

                $tb_data_str = addslashes_deep(serialize($tb_data));

                $goods_query_info .= ' ("' . $good_info['goods_name'] . '", "' . $good_info['shop_price'] . '", "' . $good_info['goods_desc'] . '", "' . $good_info['tb_iid'] . '", "' . $tb_data_str . '"),';
            }

            $sql = 'INSERT INTO ' . $ecs->table('goods') . ' (goods_name, shop_price, goods_desc, tb_iid, tb_data) VALUES' . substr($goods_query_info, 0 ,-1);
            $db->query($sql);

            ecs_header("Location: taobao_account.php?act=get_taobao_goods&page=" . $page . "&pagesize=" . $page_size);
            exit;
        }
    }
}

/**
 * 返回某个订单可执行的操作列表，包括权限判断
 * @param   array   $order      订单信息 order_status, shipping_status, pay_status
 * @param   bool    $is_cod     支付方式是否货到付款
 * @return  array   可执行的操作  confirm, pay, unpay, prepare, ship, unship, receive, cancel, invalid, return, drop
 * 格式 array('confirm' => true, 'pay' => true)
 */
function operable_list($order)
{
    /* 取得订单状态、发货状态、付款状态 */
    $os = $order['order_status'];
    $ss = $order['shipping_status'];
    $ps = $order['pay_status'];
    /* 取得订单操作权限 */
    $actions = $_SESSION['action_list'];
    if ($actions == 'all')
    {
        $priv_list  = array('os' => true, 'ss' => true, 'ps' => true, 'edit' => true);
    }
    else
    {
        $actions    = ',' . $actions . ',';
        $priv_list  = array(
            'os'    => strpos($actions, ',order_os_edit,') !== false,
            'ss'    => strpos($actions, ',order_ss_edit,') !== false,
            'ps'    => strpos($actions, ',order_ps_edit,') !== false,
            'edit'  => strpos($actions, ',order_edit,') !== false
        );
    }

    /* 取得订单支付方式是否货到付款 */
    $payment = payment_info($order['pay_id']);
    $is_cod  = $payment['is_cod'] == 1;

    /* 根据状态返回可执行操作 */
    $list = array();
    if (OS_UNCONFIRMED == $os)
    {
        /* 状态：未确认 => 未付款、未发货 */
        if ($priv_list['os'])
        {
            $list['confirm']    = true; // 确认
            $list['invalid']    = true; // 无效
            $list['cancel']     = true; // 取消
            if ($is_cod)
            {
                /* 货到付款 */
                if ($priv_list['ss'])
                {
                    $list['prepare'] = true; // 配货
                    $list['split'] = true; // 分单
                }
            }
            else
            {
                /* 不是货到付款 */
                if ($priv_list['ps'])
                {
                    $list['pay'] = true;  // 付款
                }
            }
        }
    }
    elseif (OS_CONFIRMED == $os || OS_SPLITED == $os || OS_SPLITING_PART == $os)
    {
        /* 状态：已确认 */
        if (PS_UNPAYED == $ps)
        {
            /* 状态：已确认、未付款 */
            if (SS_UNSHIPPED == $ss || SS_PREPARING == $ss)
            {
                /* 状态：已确认、未付款、未发货（或配货中） */
                if ($priv_list['os'])
                {
                    $list['cancel'] = true; // 取消
                    $list['invalid'] = true; // 无效
                }
                if ($is_cod)
                {
                    /* 货到付款 */
                    if ($priv_list['ss'])
                    {
                        if (SS_UNSHIPPED == $ss)
                        {
                            $list['prepare'] = true; // 配货
                        }
                        $list['split'] = true; // 分单
                    }
                }
                else
                {
                    /* 不是货到付款 */
                    if ($priv_list['ps'])
                    {
                        $list['pay'] = true; // 付款
                    }
                }
            }
            /* 状态：已确认、未付款、发货中 */
            elseif (SS_SHIPPED_ING == $ss || SS_SHIPPED_PART == $ss)
            {
                // 部分分单
                if (OS_SPLITING_PART == $os)
                {
                    $list['split'] = true; // 分单
                }
                $list['to_delivery'] = true; // 去发货
            }
            else
            {
                /* 状态：已确认、未付款、已发货或已收货 => 货到付款 */
                if ($priv_list['ps'])
                {
                    $list['pay'] = true; // 付款
                }
                if ($priv_list['ss'])
                {
                    if (SS_SHIPPED == $ss)
                    {
                        $list['receive'] = true; // 收货确认
                    }
                    $list['unship'] = true; // 设为未发货
                    if ($priv_list['os'])
                    {
                        $list['return'] = true; // 退货
                    }
                }
            }
        }
        else
        {
            /* 状态：已确认、已付款和付款中 */
            if (SS_UNSHIPPED == $ss || SS_PREPARING == $ss)
            {
                /* 状态：已确认、已付款和付款中、未发货（配货中） => 不是货到付款 */
                if ($priv_list['ss'])
                {
                    if (SS_UNSHIPPED == $ss)
                    {
                        $list['prepare'] = true; // 配货
                    }
                    $list['split'] = true; // 分单
                }
                if ($priv_list['ps'])
                {
                    $list['unpay'] = true; // 设为未付款
                    if ($priv_list['os'])
                    {
                        $list['cancel'] = true; // 取消
                    }
                }
            }
            /* 状态：已确认、未付款、发货中 */
            elseif (SS_SHIPPED_ING == $ss || SS_SHIPPED_PART == $ss)
            {
                // 部分分单
                if (OS_SPLITING_PART == $os)
                {
                    $list['split'] = true; // 分单
                }
                $list['to_delivery'] = true; // 去发货
            }
            else
            {
                /* 状态：已确认、已付款和付款中、已发货或已收货 */
                if ($priv_list['ss'])
                {
                    if (SS_SHIPPED == $ss)
                    {
                        $list['receive'] = true; // 收货确认
                    }
                    if (!$is_cod)
                    {
                        $list['unship'] = true; // 设为未发货
                    }
                }
                if ($priv_list['ps'] && $is_cod)
                {
                    $list['unpay']  = true; // 设为未付款
                }
                if ($priv_list['os'] && $priv_list['ss'] && $priv_list['ps'])
                {
                    $list['return'] = true; // 退货（包括退款）
                }
            }
        }
    }
    elseif (OS_CANCELED == $os)
    {
        /* 状态：取消 */
        if ($priv_list['os'])
        {
            $list['confirm'] = true;
        }
        if ($priv_list['edit'])
        {
            $list['remove'] = true;
        }
    }
    elseif (OS_INVALID == $os)
    {
        /* 状态：无效 */
        if ($priv_list['os'])
        {
            $list['confirm'] = true;
        }
        if ($priv_list['edit'])
        {
            $list['remove'] = true;
        }
    }
    elseif (OS_RETURNED == $os)
    {
        /* 状态：退货 */
        if ($priv_list['os'])
        {
            $list['confirm'] = true;
        }
    }

    /* 修正发货操作 */
    if (!empty($list['split']))
    {
        /* 如果是团购活动且未处理成功，不能发货 */
        if ($order['extension_code'] == 'group_buy')
        {
            include_once(ROOT_PATH . 'includes/lib_goods.php');
            $group_buy = group_buy_info(intval($order['extension_id']));
            if ($group_buy['status'] != GBS_SUCCEED)
            {
                unset($list['split']);
                unset($list['to_delivery']);
            }
        }

        /* 如果部分发货 不允许 取消 订单 */
        if (order_deliveryed($order['order_id']))
        {
            $list['return'] = true; // 退货（包括退款）
            unset($list['cancel']); // 取消
        }
    }

    /* 售后 */
    $list['after_service'] = true;

    return $list;
}